package com.zrfintech.api.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 复制POST请求body参数，以供拦截器读取
 * 
 * @author tangyuanliang
 *
 */
@Component
@Order(1)
public class RequestReadFilter extends GenericFilterBean {
    /** 日志. */
    private static Logger LOGGER = LoggerFactory.getLogger(RequestReadFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        LOGGER.info("[doFilter] RequestReadFilter");
        try {
            ServletRequest requestWrapper = null;
            if (request instanceof HttpServletRequest) {
                requestWrapper = new HttpServletRequestRead((HttpServletRequest) request);
            }
            if (null == requestWrapper) {
                chain.doFilter(request, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }
        } catch (Exception e) {
            LOGGER.error("[doFilter]exception.", e);
        }
    }

}
